import React, {Component} from 'react'
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux'
import { getContact ,storeCount ,setErrorName ,setErrorEmail ,setEmailFormatError ,setErrorMessage } from '../../../actions/contact/index';
import {isEmail} from '../../../static/js/global'

import Button from 'antd/lib/button';
import Input from 'antd/lib/input';
import Form from 'antd/lib/form';
import Toast from 'antd-mobile/lib/toast';
const FormItem = Form.Item;
import Row from 'antd/lib/row';
import Col from 'antd/lib/col';
import Icon from 'antd/lib/icon';
const {TextArea} = Input;

class ContactUs extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            iconLoading: false
        }
    }

    handleSubmit = (e) => {
        e.preventDefault();

        this.props.form.validateFields((err, values) => {
            if (!err) {
                if(!values.name){
                    this.props.setErrorName(true);
                    return;
                }else{
                    this.props.setErrorName(false);
                }
                if(!values.email){
                    this.props.setErrorEmail(true);
                    return;
                }else{
                    this.props.setErrorEmail(false);
                }
                if(values.email && !isEmail(values.email)){
                    this.props.setErrorEmail(true);
                    this.props.setEmailFormatError(true);
                    return;
                }else{
                    this.props.setErrorEmail(false);
                    this.props.setEmailFormatError(false);
                }
                if(!values.content){
                    this.props.setErrorMessage(true);
                    return;
                }else{
                    this.props.setErrorMessage(false);
                }
                this.setState({
                    iconLoading: true
                });
                this.props.getContact(values)
                    .then((res) => {
                        this.setState({
                            iconLoading: false
                        });
                        if(res.data.success) {
                            Toast.success('commit success!', 1);
                        }
                    })
                    .catch((err) => {
                        this.setState({
                            iconLoading: false
                        });
                    });
                this.props.form.resetFields();
                this.props.form.validateFields();
                this.props.storeCount(0)
            }
        });
    };

    render() {
        const {contact,home} = this.props;
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: {
                    span: 24
                },
                sm: {
                    span: 6
                },
            },
            wrapperCol: {
                xs: {
                    span: 24
                },
                sm: {
                    span: 14
                },
            },
        };
        const tailFormItemLayout = {
            wrapperCol: {
                xs: {
                    span: 24,
                    offset: 0,
                },
                sm: {
                    span: 14,
                    offset: 6,
                },
            },
        };
        return (
			<div className='conbox'>
				<h1>Contact Us</h1>
				<div className="bor_bt"></div>
                <Form onSubmit={this.handleSubmit}>
                    <FormItem {...formItemLayout} label={(<span className="form-span">Name&nbsp;<em className="form-em">*</em></span>)} className={home.isFb? (contact.errorName ? 'labN-FB labN error-input' : 'labN-FB labN') : (contact.errorName ? 'labN error-input' : 'labN')}>
                        {getFieldDecorator('name', {rules: [{message: 'name'}]})(
                            <Input />
                        )}
                    </FormItem>
                    <Row style={{display:contact.errorName?'block':'none'}}>
                        <Col span={24}><p className={home.isFb? 'error-tip-fb' : 'error-tip-mobile'}><Icon type="exclamation-circle-o" style={{marginRight: 5}}/>name is required!</p></Col>
                    </Row>

                    <FormItem {...formItemLayout} label={(<span className="form-span">Email&nbsp;<em className="form-em">*</em></span>)} className={home.isFb? (contact.errorEmail ? 'labN-FB labN error-input' : 'labN-FB labN') : (contact.errorEmail ? 'labN error-input' : 'labN')}>
                        {getFieldDecorator('email', {rules: [{message: 'email'}]})(
                            <Input />
                        )}
                    </FormItem>
                    <Row style={{display:contact.errorEmail?'block':'none'}}>
                        <Col span={24}><p className={home.isFb? 'error-tip-fb' : 'error-tip-mobile'}><Icon type="exclamation-circle-o" style={{marginRight: 5}}/>{contact.emailFormatError?'This is not a vaild email address!':'email is required!'}</p></Col>
                    </Row>

                    <FormItem {...formItemLayout} label={(<span className="form-span">Phone Number&nbsp;</span>)} className={home.isFb? 'labN-FB labN' : 'labN'}>
                        {getFieldDecorator('phone', {rules: [{message: 'phoneNumber'}]})(
                            <Input type="number"/>
                        )}
                    </FormItem>

                    <FormItem {...formItemLayout} label={(<span className="form-span">Message&nbsp;<em className="form-em">*</em></span>)} className={home.isFb?  (contact.errorMessage ? 'labN-FB labN error-input' : 'labN-FB labN') : (contact.errorEmail ? 'labN error-input' : 'labN')}>
                        {getFieldDecorator('content', {rules: [{message: 'content'}]})(
                            <TextArea placeholder="what on your mind" className="form-textarea" maxLength="500" />
                        )}
                    </FormItem>

                    <Row style={{display:contact.errorMessage?'block':'none'}}>
                        <Col span={24}><p className={home.isFb? 'error-tip-fb' : 'error-tip-mobile'}><Icon type="exclamation-circle-o" style={{marginRight: 5}}/>message is required!</p></Col>
                    </Row>
                    <span className={home.isFb? 'count-FB count' : 'count'}>{contact.count}/500</span>

                    <FormItem {...tailFormItemLayout}  className={home.isFb? 'labN-FB labN' : 'labN'}>
                        <Button type="primary" className="form-btn"  loading={this.state.iconLoading} onClick={this.handleSubmit} >
                            Send
                        </Button>
                    </FormItem>
                </Form>
			</div>
        )
    }
}


const mapStateToProps = ({contact, home}) => ({
    contact,home
});

const mapDispatchToProps = (dispatch) => {
    return {
        getContact: bindActionCreators(getContact, dispatch),
        setErrorName: bindActionCreators(setErrorName, dispatch),
        setErrorEmail: bindActionCreators(setErrorEmail, dispatch),
        setEmailFormatError: bindActionCreators(setEmailFormatError, dispatch),
        setErrorMessage: bindActionCreators(setErrorMessage, dispatch),
        storeCount: bindActionCreators(storeCount, dispatch),
    }
};
export default connect(mapStateToProps, mapDispatchToProps)(Form.create({
    onValuesChange(_, values) {
        if(values.content){
            let count = values.content.length;
            window.__NEXT_REDUX_STORE__.dispatch(storeCount(count));
            window.__NEXT_REDUX_STORE__.dispatch(setErrorMessage(false));
        }
        if(values.name){
            window.__NEXT_REDUX_STORE__.dispatch(setErrorName(false))
        }
        if(values.email) {
            window.__NEXT_REDUX_STORE__.dispatch(setErrorEmail(false));
            if(!isEmail(values.email)) {
                window.__NEXT_REDUX_STORE__.dispatch(setEmailFormatError(true))
            }else {
                window.__NEXT_REDUX_STORE__.dispatch(setEmailFormatError(false))
            }
        }
    }
})(ContactUs))